<?php

namespace Xin\EasyQueue;

use DateTimeInterface;
use Hyperf\Context\ApplicationContext;
use Xin\EasyQueue\Webman\RedisQueueInfo;
use function Hyperf\Config\config;

class Queue
{
    /**
     * 分发队列任务
     * @param mixed $data
     * @param int|DateTimeInterface $delay
     * @param string|null $queue
     * @param string|null $connection
     * @return PendingDispatch
     */
    public static function dispatch($data, $delay = 0, string $queue = null, string $connection = null): PendingDispatch
    {
        if (!$queue) {
            $queue = self::getDefaultQueueName();
            if (is_object($data) && property_exists($data, 'queue') && $data->queue) {
                $queue = $data->queue;
            }
        }

        if (!$connection) {
            $connection = self::getDefaultConnectionName();
            if (is_object($data) && property_exists($data, 'connection') && $data->connection) {
                $connection = $data->connection;
            }
        }

        return (new PendingDispatch($data, $queue, $connection))->delay($delay);
    }

//    /**
//     * 获取队列实例
//     * @param string|null $queue
//     * @param string|null $connection
//     * @return PendingDispatch
//     */
//    public static function queue(string $queue = null, string $connection = null): PendingDispatch
//    {
//        $queue = $queue ?: self::getDefaultQueueName();
//        $connection = $connection ?: self::getDefaultConnectionName();
//    }

    /**
     * 获取队列的信息
     * @param string|null $queue
     * @param string|null $connection
     * @return RedisQueueInfo
     */
    public static function info(string $queue = null, string $connection = null)
    {
        $queue = $queue ?: self::getDefaultQueueName();
        $connection = $connection ?: self::getDefaultConnectionName();
        return new RedisQueueInfo($queue, $connection);
    }

    /**
     * @return string
     */
    public static function getDefaultQueueName(): string
    {
        if (class_exists(ApplicationContext::class)) {
            return key(config('async_queue'));
        }

        return env('QUEUE_DEFAULT', 'default');
    }

    /**
     * @return string
     */
    public static function getDefaultConnectionName(): string
    {
        if (class_exists(ApplicationContext::class)) {
            $key = key(config('async_queue'));
            return config('async_queue.' . $key . '.redis.pool');
        }

        return env('QUEUE_CONNECTION', 'default');
    }
}
